package com.ruoyi.web.controller.system;


import java.util.concurrent.TimeUnit;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.WeChatConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import com.ruoyi.system.service.ISysUserService;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.system.mapper.SysUserMapper;

import static com.ruoyi.common.core.domain.AjaxResult.success;

/**
 * 第三方认证授权处理
 *
 * @author ruoyi
 */
@Anonymous
@RestController
public class SysAuthController
{
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysConfigMapper configMapper;
    @Autowired
    private WeChatConfig weChatConfig;

    @GetMapping("/socialLogin/{code}")
    public AjaxResult socialLogin(@PathVariable("code") String code)
    {
        AjaxResult ajax = success();
        if (StringUtils.isNull(code)){
            return AjaxResult.error( "认证失败，未获取到code,请联系管理员。");
        }
        //登录参数
        String token = null;

        //code
        String wxCode = code;
        //企业ID
        String corpid = weChatConfig.getCorpid();
        //凭证
        String corpsecret = weChatConfig.getCorpsecret();
        //用户信息链接
        String userUrl;
        //access_token链接
        String tokenUrl = weChatConfig.getTokenUrl()+"?corpid="+corpid+"&corpsecret="+corpsecret;

        String accessToken;
        //redis中的access_token
        accessToken = redisCache.getCacheObject("access_token");
        if(StringUtils.isNull(accessToken)){
            //获取微信认证access_token
            String tokenResult = HttpUtils.sendGet(tokenUrl);
            if(StringUtils.isNotNull(tokenResult)){
                JSONObject json = JSONObject.parseObject(tokenResult);
                accessToken = json.getString("access_token");
                String timeOut = json.getString("expires_in");
                redisCache.setCacheObject("access_token", accessToken, Integer.parseInt(timeOut), TimeUnit.SECONDS);
            }else {
                return AjaxResult.error( "认证失败，token获取失败，请联系管理员。");
            }
        }
        userUrl = weChatConfig.getUserUrl()+"?access_token="+accessToken+"&code="+wxCode;
        String userResult = HttpUtils.sendGet(userUrl);

        if (StringUtils.isNotNull(userResult)){

            JSONObject userJson = JSONObject.parseObject(userResult);
            String errcode = userJson.getString("errcode");
            if ("0".equals(errcode)){
                String userid = userJson.getString("userid");
                String userTicket = userJson.getString("user_ticket");
                //成员详细信息
                //https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&userid=USERID
                String userInfoUrl = weChatConfig.getUserInfoUrl()+"?access_token="+accessToken+"&userid="+userid;
                //String params = "{\"user_ticket\": \""+userTicket+"\"}";
                String userInfoResult = HttpUtils.sendGet(userInfoUrl);
                //String userInfoResult = HttpUtils.sendPost(userInfoUrl,params);
                if(StringUtils.isNotNull(userInfoResult)){
                    JSONObject userInfoJson = JSONObject.parseObject(userInfoResult);
                    String infoUserid = userInfoJson.getString("userid");
                    String userNick = userInfoJson.getString("name");
                    String mobile = userInfoJson.getString("telephone");

                    SysUser user = null;
                    if (StringUtils.isNotNull(mobile)){
                        user = sysUserService.selectUserByUserName(mobile);
                    }
                    if (StringUtils.isNull(user)){
                        user = sysUserService.selectUserByUserName(infoUserid);
                    }

                    if (StringUtils.isNotNull(user)){
                        LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
                        token = tokenService.createToken(loginUser);

                    }else {
                        SysUser newUser = new SysUser();
                        if (StringUtils.isNotNull(mobile)){
                            newUser.setUserName(mobile);
                        }else {
                            newUser.setUserName(infoUserid);
                        }
                        newUser.setNickName(userNick);
                        SysConfig sysConfig = configMapper.checkConfigKeyUnique("sys.user.initPassword");
                        if (StringUtils.isNotNull(sysConfig)){
                            newUser.setPassword(SecurityUtils.encryptPassword(sysConfig.getConfigValue()));
                        }
                        newUser.setPhonenumber(mobile);
                        newUser.setIsFormalworker("Y");
                        Long[] tempArr = {2L};
                        newUser.setRoleIds(tempArr);
                        newUser.setSsmId(3L);
                        newUser.setLevelId(6L);
                        newUser.setEntryDate(DateUtils.getNowDate());
                        sysUserService.insertUser(newUser);

                        LoginUser loginUser = new LoginUser(newUser.getUserId(), newUser.getDeptId(), newUser, permissionService.getMenuPermission(newUser));
                        token = tokenService.createToken(loginUser);

                    }

                }else{
                    return AjaxResult.error( "认证失败，获取用户信息失败，请联系管理员。");
                }
            }
        }else {
            return AjaxResult.error( "认证失败，未获取到用户信息，请联系管理员。");
        }

        if(StringUtils.isNull(token)){
            return AjaxResult.error( "登录失败，请联系管理员。");
        }

        return success().put(Constants.TOKEN, token);
        //return AjaxResult.success(Constants.TOKEN, token);
    }

}
